<template>
  <div class="basic-info-edit">
    <div class="header">
      <el-icon class="back-icon" @click="router.back()">
        <ArrowLeft />
      </el-icon>
      <span class="title">个人信息</span>
    </div>

    <div class="edit-list">
      <!-- 头像 -->
      <div class="edit-item">
        <span class="label">头像</span>
        <div class="value-wrapper">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileUrl"
            :headers="{ Authorization: 'Bearer ' + token }"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="formData.avatar" :src="formData.avatar.startsWith('http') ? formData.avatar : base.baseUrl + formData.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </div>
      </div>

      <!-- 姓名 -->
      <div class="edit-item">
        <span class="label">姓名</span>
        <div class="value-wrapper">
          <el-input
            v-model="formData.name"
            placeholder="请输入姓名"
            @change="updateField('name')"
          />
        </div>
      </div>

      <!-- 手机号 -->
      <div class="edit-item">
        <span class="label">手机号</span>
        <div class="value-wrapper">
          <el-input
            v-model="formData.phone"
            placeholder="请输入手机号"
            @change="updateField('phone')"
          />
        </div>
      </div>

      <!-- 邮箱 -->
      <div class="edit-item">
        <span class="label">邮箱</span>
        <div class="value-wrapper">
          <el-input
            v-model="formData.email"
            placeholder="请输入邮箱"
            @change="updateField('email')"
          />
        </div>
      </div>

      <!-- 个人介绍 -->
      <div class="edit-item">
        <span class="label">个人介绍</span>
        <div class="value-wrapper">
          <el-input
            v-model="formData.introduction"
            type="textarea"
            :rows="3"
            placeholder="请输入个人介绍"
            @change="updateField('introduction')"
          />
        </div>
      </div>

      <!-- 修改密码区域 -->
      <div class="edit-item">
        <span class="label">密码</span>
        <div class="value-wrapper">
          <el-button type="primary" @click="handleOpenPasswordDialog">修改密码</el-button>
        </div>
      </div>

      <!-- 修改密码弹窗 -->
      <el-dialog v-model="passwordDialogVisible" title="修改密码" width="400px">
        <div class="password-form">
          <el-form :model="passwordForm" label-width="100px">
            <el-form-item label="旧密码">
              <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入旧密码" />
            </el-form-item>
            <el-form-item label="新密码">
              <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" />
            </el-form-item>
            <el-form-item label="确认新密码">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" />
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleChangePassword">确认修改</el-button>
        </template>
      </el-dialog>

      <!-- 只有咨询师可见 -->
      <div v-if="isCounselor" class="edit-item">
        <span class="label">预约空闲时间</span>
        <div class="value-wrapper">
          <span
            class="free-time-link"
            @click="handleOpenFreeTimeDialog"
          >
            {{
              freeTimeListShow.length
                ? freeTimeListShow.map(item => `${item.date} ${item.time_slots.join(', ')}`).join('，')
                : '点击设置空闲时间'
            }}
          </span>
        </div>
      </div>
      <el-dialog v-model="freeTimeDialogVisible" title="修改预约空闲时间" width="500px">
        <div class="free-time-container">
          <div class="date-picker-container">
            <el-date-picker
              v-model="selectedDate"
              type="date"
              placeholder="选择日期"
              style="width: 100%; margin-bottom: 16px;"
              @change="handleDateSelect"
            />
          </div>
          <div class="time-slots-container">
            <div class="time-slots-title">选择时段：</div>
            <div class="time-slots-buttons">
            <el-button
              v-for="slot in TIME_SLOTS"
              :key="slot"
                :type="selectedTimeSlots.includes(slot) ? 'primary' : 'default'"
                @click="toggleTimeSlot(slot)"
              style="margin: 4px;"
            >
              {{ slot }}
              </el-button>
            </div>
            <el-button
              type="primary"
              @click="addNewFreeTime"
              style="margin-top: 16px;"
            >
              {{ isUpdateMode ? '更新到列表' : '添加到列表' }}
            </el-button>
          </div>
          <div class="selected-times" v-if="freeTimeList.length > 0">
            <div class="selected-times-title">已选择的时间：</div>
            <div v-for="(item, idx) in freeTimeList" :key="idx" class="selected-time-item">
              <span>{{ item.date }} {{ item.time_slots.join(', ') }}</span>
              <el-button type="danger" icon="el-icon-delete" @click="removeFreeTime(idx)" circle size="small" />
            </div>
          </div>
        </div>
        <template #footer>
          <el-button @click="freeTimeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddFreeTime">保存</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Plus } from '@element-plus/icons-vue'
import { Api } from '@/api'
import base from '@/api/base.js'
import { useUserStore } from '@/stores/user.js'

const TIME_SLOTS = [
  '09:00-10:00',
  '10:00-11:00',
  '11:00-12:00',
  '14:00-15:00',
  '15:00-16:00',
  '16:00-17:00'
]

const router = useRouter()
const userStore = useUserStore()
const token = ref(userStore.token)
const uploadFileUrl = base.baseUrl + base.uploadFiles

// 判断是否为咨询师
const isCounselor = computed(() => !!userStore.user?.is_counselor)

// 控制弹窗显示
const freeTimeDialogVisible = ref(false)
const freeTimeList = ref([])
const selectedDate = ref('')
const selectedTimeSlots = ref([])
const isUpdateMode = ref(false)

// 打开弹窗时初始化
const handleOpenFreeTimeDialog = () => {
  try {
    freeTimeList.value = JSON.parse(userStore.user.counselor_free_time || '[]')
  } catch {
    freeTimeList.value = []
  }
  selectedDate.value = ''
  selectedTimeSlots.value = []
  isUpdateMode.value = false
  freeTimeDialogVisible.value = true
}

// 监听日期选择
const handleDateSelect = async (date) => {
  if (!date) {
    selectedTimeSlots.value = []
    isUpdateMode.value = false
    return
  }

  const formattedDate = formatDate(date)
  try {
    // 获取咨询师空闲时间
    const res = await Api.getCounselorFreeTime({
      counselor_id: userStore.user.id
    })
    if (res.data.status === 200 && res.data.data) {
      // 查找选中日期的数据
      const dateData = res.data.data.find(item => item.date === formattedDate)
      if (dateData) {
        // 如果存在该日期的数据，显示已选择的时段
        selectedTimeSlots.value = dateData.time_slots || []
        isUpdateMode.value = true
      } else {
        // 如果没有该日期的数据，清空选择
        selectedTimeSlots.value = []
        isUpdateMode.value = false
      }
    } else {
      // 如果没有数据，清空选择
      selectedTimeSlots.value = []
      isUpdateMode.value = false
    }
  } catch (error) {
    console.error('获取空闲时间失败:', error)
    ElMessage.error('获取空闲时间失败，请稍后再试')
    selectedTimeSlots.value = []
    isUpdateMode.value = false
  }
}

// 切换时段选中状态
const toggleTimeSlot = (slot) => {
  const index = selectedTimeSlots.value.indexOf(slot)
  if (index > -1) {
    selectedTimeSlots.value.splice(index, 1)
  } else {
    selectedTimeSlots.value.push(slot)
  }
}

// 添加新的空闲时间到列表
const addNewFreeTime = () => {
  if (!selectedDate.value || selectedTimeSlots.value.length === 0) {
    ElMessage.error('请选择日期和时段')
    return
  }

  const formattedDate = formatDate(selectedDate.value)
  // 检查是否已存在相同日期的记录
  const existingIndex = freeTimeList.value.findIndex(item => item.date === formattedDate)

  if (existingIndex > -1) {
    // 如果存在，更新时段
    freeTimeList.value[existingIndex].time_slots = [...selectedTimeSlots.value]
    ElMessage.success(isUpdateMode.value ? '时段已更新到列表' : '时段已添加到列表')
  } else {
    // 如果不存在，添加新记录
    freeTimeList.value.push({
      date: formattedDate,
      time_slots: [...selectedTimeSlots.value]
    })
    ElMessage.success('时段已添加到列表')
  }

  // 清空选择
  selectedDate.value = ''
  selectedTimeSlots.value = []
  isUpdateMode.value = false
}

// 添加空闲时间
const handleAddFreeTime = async () => {
  // 校验
  if (freeTimeList.value.length === 0) {
    ElMessage.error('请至少添加一个空闲时间')
      return
    }
  try {
    // 获取咨询师空闲时间
    const res = await Api.getCounselorFreeTime({
      counselor_id: userStore.user.id
    })
    if (res.data.status === 200 && res.data.data) {
      // 获取数据库中已存在的日期
      const existingDates = res.data.data.map(item => item.date)

      // 逐个处理列表中的每个日期
      for (const item of freeTimeList.value) {
        if (existingDates.includes(item.date)) {
          // 如果日期已存在，使用更新接口
          const updateRes = await Api.updateCounselorFreeTime({
            id: userStore.user.id,
            counselor_free_time: [item]
          })
          if (updateRes.data.status !== 200) {
            throw new Error(updateRes.data.message || `更新日期 ${item.date} 失败`)
          }
        } else {
          // 如果日期不存在，使用添加接口
          const addRes = await Api.addCounselorFreeTime({
      id: userStore.user.id,
            counselor_free_time: [item]
    })
          if (addRes.data.status !== 200) {
            throw new Error(addRes.data.message || `添加日期 ${item.date} 失败`)
          }
        }
      }

      ElMessage.success('空闲时间已保存')
      userStore.setUser({
        ...userStore.user,
        counselor_free_time: freeTimeList.value
      })
      freeTimeDialogVisible.value = false
    } else {
      // 如果没有现有数据，直接添加所有日期
      const addRes = await Api.addCounselorFreeTime({
        id: userStore.user.id,
        counselor_free_time: freeTimeList.value
      })
      if (addRes.data.status === 200) {
        ElMessage.success('空闲时间已添加')
        userStore.setUser({
          ...userStore.user,
          counselor_free_time: freeTimeList.value
        })
        freeTimeDialogVisible.value = false
      } else {
        throw new Error(addRes.data.message || '添加失败')
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || '操作失败，请稍后再试')
  }
}

// 表单数据
const formData = reactive({
  ...userStore.user
})

// 密码修改表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 控制密码修改弹窗显示
const passwordDialogVisible = ref(false)

// 打开密码修改弹窗
const handleOpenPasswordDialog = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordDialogVisible.value = true
}

const handleChangePassword = async () => {
  if (!passwordForm.oldPassword || !passwordForm.newPassword || !passwordForm.confirmPassword) {
    ElMessage.error('请填写完整的密码信息')
    return
  }
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    ElMessage.error('两次输入的新密码不一致')
    return
  }
  try {
    const response = await Api.updatePassword({
      id: userStore.user.id,
      oldPassword: passwordForm.oldPassword,
      password: passwordForm.newPassword
    })
    if (response.data.status === 200) {
      ElMessage.success('密码修改成功')
      passwordDialogVisible.value = false
      // 清空表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    } else {
      throw new Error(response.data.message || '密码修改失败')
    }
  } catch (error) {
    console.error('密码修改失败:', error)
    ElMessage.error(error.message || '密码修改失败，请稍后再试')
  }
}

const updateField = async (field) => {
  try {
    const value = formData[field]
    if (!value && field !== 'introduction') {
      ElMessage.error('内容不能为空')
      return
    }

    const payload = {
      id: userStore.user.id,
      [field]: value
    }

    let response
    if (field === 'introduction') {
      response = await Api.updateIntroduction(payload)
    } else {
      response = await Api.updateUser(payload)
    }

    if (response.data.status === 200) {
      ElMessage.success('修改成功')
      userStore.setUser({
        ...userStore.user,
        [field]: value
      })
    } else {
      throw new Error(response.data.message || '修改失败')
    }
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('更新失败，请稍后再试')
  }
}

// 上传头像
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  return true
}

const handleAvatarSuccess = async (res) => {
  if (res.status === 200) {
    formData.avatar = res.data.filePath
    try {
      await Api.updateUser({
        id: userStore.user.id,
        avatar: formData.avatar
      })
      userStore.setUser({
        ...userStore.user,
        avatar: formData.avatar
      })
      ElMessage.success('头像更新成功')
    } catch (error) {
      console.error('更新头像失败:', error)
      ElMessage.error('更新头像失败，请稍后再试')
    }
  } else {
    ElMessage.error('头像上传失败')
  }
}

// 显示用的空闲时间
const freeTimeListShow = computed(() => {
  try {
    return JSON.parse(userStore.user.counselor_free_time || '[]')
  } catch {
    return []
  }
})

// 日期格式化函数，避免toISOString带来的时区问题
const formatDate = (date) => {
  if (typeof date === 'string') return date
  if (date instanceof Date) {
    const y = date.getFullYear()
    const m = (date.getMonth() + 1).toString().padStart(2, '0')
    const d = date.getDate().toString().padStart(2, '0')
    return `${y}-${m}-${d}`
  }
  return ''
}

const removeFreeTime = (idx) => {
  freeTimeList.value.splice(idx, 1)
}
</script>

<style scoped>
.basic-info-edit {
  background-color: #f7f8fa;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  padding: 10px 16px;
  background-color: white;
  border-bottom: 1px solid #f0f0f0;
}

.back-icon {
  font-size: 20px;
  cursor: pointer;
  margin-right: 16px;
}

.title {
  font-size: 16px;
  font-weight: 500;
}

.edit-list {
  background-color: white;
  margin-top: 10px;
}

.edit-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.edit-item:last-child {
  border-bottom: none;
}

.label {
  color: #333;
  font-size: 16px;
  width: 120px;
  flex-shrink: 0;
  white-space: nowrap;
}

.value-wrapper {
  flex: 1;
  margin-left: 20px;
}

:deep(.el-input__wrapper) {
  background-color: transparent;
  box-shadow: none;
}

:deep(.el-input__inner) {
  color: #666;
  font-size: 14px;
}

:deep(.el-textarea__inner) {
  background-color: transparent;
  color: #666;
  font-size: 14px;
  padding: 0;
  min-height: auto !important;
}

.avatar-uploader :deep(.avatar) {
  width: 60px;
  height: 60px;
  border-radius: 3px;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 3px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
}

.free-time-link {
  color: #409EFF;
  cursor: pointer;
  text-decoration: underline;
  font-size: 16px;
}

.free-time-container {
  padding: 16px;
}

.date-picker-container {
  margin-bottom: 20px;
}

.time-slots-container {
  margin-bottom: 20px;
}

.time-slots-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
}

.time-slots-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.selected-times {
  margin-top: 20px;
}

.selected-times-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
}

.selected-time-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 8px;
}
</style>
